// var DB = require("../lib/db_pg").DB;
var DB = require("../lib/db_mysql").DB;
var config = require('../lib/config');
var resErr = require('../lib/util.js').resErr;
var md5 = require('../lib/util.js').md5;
var async = require('async');
var http_request = require('../lib/util.js').http_request;

exports.login_default = function(req, res){
    if(req.session.adminuser){
        res.redirect('/admin/index.html');
    }else{
        res.redirect('/login.html');
    }
};

exports.login_ownpwd_admin = function(req,res) {
  console.log('admin_user login...');
  var user_name = req.param('user_name');
  var user_password = req.param("user_password");
  if(!user_name || !user_password){
    return resErr(res,'请输入用户名或密码！');
  }
  /*var verifyCode = req.param('verifyCode');
  if(!verifyCode) {
    return resErr(res, '验证码不能为空！');
  }
  if(verifyCode != req.session.captcha) {
    return resErr(res, '验证码不正确！');
  }*/
  req.session.adminuser = null;
  user_password = md5(user_password);
  console.log('user_name: '+user_name);
  console.log('user_password: '+user_password);
  var db = new DB();
  async.waterfall([
    function(cb){
      if(!req.session.adminuser){
        var tmp_params = [];
        var sql_text = "select * from t_sys_user where (user_name = ? or user_realname = ?)and user_password = ?";
        tmp_params.push(user_name);
        tmp_params.push(user_name);
        tmp_params.push(user_password);
        db.query(sql_text,tmp_params,function(err,rows){
          if(err) return cb(err);
          if(rows.length > 0){
            req.session.adminuser = rows[0];
          } else {
            return cb('用户名或密码错误！');
          }
          return cb(null);
        });
      }
      else{
        return cb(null);      
      }
    },
    function(cb){
      if(req.session.adminuser){
        var sql = "select r.* from t_sys_role r,t_sys_user_role ru where r.role_id = ru.role_id and ru.user_id = ?";
        db.queryMap(sql,[req.session.adminuser.user_id],function(err,data){
          if(err) return cb(err);
          req.session.adminuser.role = data;
          return cb(null);
        })
      }
    },
    function(cb){
      if(req.session.adminuser){
        var user_id = req.session.adminuser.user_id;
        var sql = "";
        sql += "SELECT                                               ";
        sql += "  res_id,                                            ";
        sql += "  res_name,                                          ";
        sql += "  parent_res_id,                                     ";
        sql += "  (SELECT                                            ";
        sql += "     r.res_name                                      ";
        sql += "   FROM t_sys_resource r                             ";
        sql += "   WHERE r.res_id = parent_res_id) parent_res_name,  ";
        sql += "  res_key,                                           ";
        sql += "  res_type,                                          ";
        sql += "  res_url,                                           ";
        sql += "  res_sorder,                                        ";
        sql += "  res_desc,                                          ";
        sql += "  icon,                                              ";
        sql += "  res_enable                                         ";
        sql += "FROM t_sys_resource                                  ";
        sql += "WHERE res_id IN(SELECT                               ";
        sql += "                  res_id                             ";
        sql += "                FROM t_sys_resource_role             ";
        sql += "                WHERE role_id IN(SELECT              ";
        sql += "                                   role_id           ";
        sql += "                                 FROM t_sys_user_role";
        sql += "                                 WHERE user_id = ?))";
        var params = [];
        params.push(user_id);
        db.query(sql,params,function(err,datas){
          if(err) return cb(err);
          var grantedAuths = [];
          if(datas.length > 0){
            for(var i=0;i<datas.length;i++){
              var res = {};
              res.resUrl = datas[i].res_url;
              grantedAuths.push(res);
            }
          }
          //放入已授权资源
          req.session.adminuser.grantedAuths = grantedAuths;
          return cb(null);
        });
      } else {
        return cb(null);
      }
    }
  ],function(err){
    if(err) return resErr(res,err);
    if(req.session.adminuser){
      if(req.param("no_redirect")){
        return res.jsonp({"success":true});
      }
      return res.json({success: true});
    }else{
      return resErr(res,'用户名或密码错误！');
    }
  })
}

exports.adminuser_list = function(req,res){
  var user_name = req.param('user_name');
  var sql_text = "SELECT u.*,case  when user_type = 1 then '老师' when user_type = 3 then '主任' end as user_title FROM t_sys_user u WHERE 1=1";
  var tmp_params = [];
  var i=1;
  if(req.param('status')){
    sql_text += " and u.status=?";
    tmp_params.push(req.param('status'));
  }
  if(user_name) {
    sql_text += " and (u.user_name like '%"+user_name+"%' or u.user_realname like '%"+user_name+"%')"
  }
  var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
  var page  = parseInt(req.param("page") || req.param("pageNum") || '1');  
  if(req.param("sort")){
    sql_text += " order by u." + req.param("sort");
    if(req.param("dir")){
      sql_text += " " + req.param("dir");
    }
  }
  var db = new DB();
  db.queryPage(sql_text,tmp_params,page,limit,function(err,result){
    if(err) return resErr(res, err);
    return res.json(result);
  })
}

exports.adminuser_add = function(req,res){
  var user_name = req.param('user_name');
  if(!user_name) return res.json({success:false,msg:'用户登录名不能为空！'});
  var user_realname = req.param('user_realname');
  if(!user_realname) return res.json({success:false,msg:'用户姓名不能为空！'})
  var user_password = req.param('user_password');
  if(!user_password) return res.json({success:false,msg:'用户登陆密码不能为空！'});

  var user_email = req.param('user_email');
  var user_phone= req.param('user_phone');
  var user_type = req.param('user_type');

  var db = new DB();
  async.waterfall([
    function(cb){
      var tmp_params = [];
      sql_text = "select count(1) counter from t_sys_user where user_name = ?";
      // console.log(sql_text);
      tmp_params.push(user_name);
      db.query(sql_text,tmp_params,function(err,datas){
        if(err) return cb(err);
        if(datas.length > 0 && datas[0].counter > 0){
          return cb('用户名已经存在！');
        }
        return cb(null);
      })
    }
  ],function(err){
    if(err) return resErr(res,err);
    var sql_text = "insert into t_sys_user set user_name=?,user_realname=?,user_password=?,user_email=?,user_phone=?,user_type=?,status=0";
    var tmp_params = [];
    user_password = md5(user_password);
    tmp_params.push(user_name);
    tmp_params.push(user_realname);
    tmp_params.push(user_password);
    tmp_params.push(user_email);
    tmp_params.push(user_phone);
    tmp_params.push(user_type);
    db.query(sql_text,tmp_params,function(err,datas){
      console.log(datas);
      if (err){
        return resErr(res,err);
      }      
      return res.json({success:true,msg:'用户添加成功！'});
    })
  })
}

exports.adminuser_upd = function(req,res){
  var user_id = req.param('user_id');
  if(!user_id) return res.json({success:false,msg:'用户ID不能为空！'});
  var user_name = req.param('user_name');
  if(!user_name) return res.json({success:false,msg:'用户名不能为空！'});
  var user_realname = req.param('user_realname');
  if(!user_realname) return res.json({success:false,msg:'用户姓名不能为空！'})
  var user_password = req.param('user_password');

  var user_email = req.param('user_email');
  var user_phone= req.param('user_phone');
  var user_type = req.param('user_type');

  var db = new DB();
  async.waterfall([
    function(cb){
      var tmp_params = [];
      sql_text = "select count(1) counter from t_sys_user where user_name = ? and user_id <> ?";
      console.log(sql_text);
      tmp_params.push(user_name);
      tmp_params.push(user_id);
      db.query(sql_text,tmp_params,function(err,datas){
        if(err) return cb(err);
        if(datas.length > 0 && datas[0].counter > 0){
          return cb('用户名已经存在！');
        }
        return cb(null);
      })
    }
  ],function(err){
    if(err) return resErr(res,err);
    var tmp_params = [];
    var sql_text = "update t_sys_user set user_name=?,user_realname=? ";
    tmp_params.push(user_name);
    tmp_params.push(user_realname);
    if(user_password){
      sql_text += ",user_password=? ";
      user_password = md5(user_password);
      tmp_params.push(user_password);
    } 
    if(user_email) {
      sql_text += ",user_password=? ";
      tmp_params.push(user_email);
    }
    if(user_phone) {
      sql_text += ",user_phone=? ";
      tmp_params.push(user_phone);
    }
    if(user_type) {
      sql_text += ",user_type=? ";
      tmp_params.push(user_type);
    }

    sql_text += " where user_id=?";
    tmp_params.push(user_id);
    db.query(sql_text,tmp_params,function(err,datas){
      //console.log(datas);
      if (err){
        return res.json({success:false,msg:JSON.stringify(err)});
      }      
      return res.json({success:true,msg:'修改成功！'});
    })
  })
}

exports.adminuser_del = function(req,res){
  var user_id = req.param('user_id');
  var sqls = {
    'deleteUserRoleSQL': 'DELETE FROM user_role WHERE user_id=?',
    'deleteUserSQL': 'DELETE FROM t_sys_user WHERE user_id=?'
  };
  var tasks = ['deleteUserRoleSQL', 'deleteUserSQL'];
  user_id = parseInt(user_id);
  var tmp_params = [];
  tmp_params.push(user_id);
  var db = new DB();
  async.eachSeries(tasks, function (item, callback) {
      console.log(item + " ==> " + sqls[item]);
      db.query(sqls[item], tmp_params, function (err, datas) {
          if(err) return res.json({success:false,msg:JSON.stringify(err)});
          callback(null);
      });
  }, function (err) {
      if(err) return res.json({success:false,msg:JSON.stringify(err)});
      return res.json({success:true,msg:'用户删除成功！'});
  });
}

  cache_token_session = function(req, token) {
    if ((token != null ? token.login_type : void 0) === "oa") {
      req.session.admin_token = {};
      req.session.admin_token.access_token = token.access_token;
      req.session.admin_token.refresh_token = token.refresh_token;
      req.session.admin_token.expires_in = token.expires_in;
      req.session.admin_token.user_id = token.user_id;
      return req.session.admin_token.scope = token.scope;
    }
  };

exports.adminuser_session = function(req,res){
  //return res.jsonp(req.session.adminuser);
  if(req.session.adminuser)
    return res.json({success:true,user_name:req.session.adminuser.user_name,user_id:req.session.adminuser.user_id,user_realname:req.session.adminuser.user_realname,adminuser:req.session.adminuser});
  else
    return res.json({success:false});
}

exports.adminuser_logout = function(req,res) {
  if(req.session.adminuser)
    req.session.adminuser = null;
  if(req.session)
    req.session.destroy();
  return res.json({success:true,msg:'退出成功！'});
}

//获取用户菜单
exports.adminuser_menu = function(req,res){
  // var user_name = req.param('user_name');
  // var user_id = req.param('user_id');
  var admin_user = req.session.adminuser;
  var user_id = admin_user.user_id;
  var user_name = admin_user.user_name;
  var sql_text = "SELECT * FROM (SELECT t.*,(SELECT r.res_name FROM t_sys_resource r WHERE r.res_id = t.parent_res_id) parentName FROM t_sys_resource t WHERE t.res_enable=0 AND t.res_id IN (SELECT res_id FROM t_sys_resource_role WHERE role_id IN (SELECT a.role_id FROM t_sys_user_role a,t_sys_user b WHERE a.user_id=b.user_id AND b.user_name='"+user_name+"'))) ta WHERE ta.parent_res_id=0 ORDER BY ta.res_sorder ASC";
  var tmp_params = [];
  var db = new DB();
  db.query(sql_text,tmp_params,function(err,datas){
    //console.log(datas);
    if(err) return resErr(res,err);
    async.eachSeries(datas,function(item,callback){
      //console.log(item);
      var sql_text2 = "SELECT * FROM (SELECT t.*,(SELECT r.res_name FROM t_sys_resource r WHERE r.res_id = t.parent_res_id) parentName FROM t_sys_resource t WHERE t.res_enable=0 AND t.res_id IN (SELECT res_id FROM t_sys_resource_role WHERE role_id IN (SELECT a.role_id FROM t_sys_user_role a,t_sys_user b WHERE a.user_id=b.user_id AND b.user_name='"+user_name+"')) ORDER BY t.res_sorder ASC) ta WHERE ta.parent_res_id="+item.res_id;
      //console.log(sql_text2);
      db.query(sql_text2,[],function(err,sub_datas){
        if(err) return callback(err);
        //console.log(sub_datas);
        item.sub_categorys = sub_datas;
        return callback(null);
      });
    },function(err){
      if(err) return res.json({success:false,msg:err});
      return res.json(getResourceTree(datas));
    });    
  })
}

exports.user_types = function(req, res){
  return res.json({
    count: 2,
    data: [
      {user_type: '1', title_name: '老师'},
      {user_type: '3', title_name: '主任'}
    ],
    pageSize: 20,
    pageNum: 1,
    pageCount: 1
  });
}

//生成树结构数组
function getResourceTree(datas) {
  if(datas) {
    var root_children_list = [];
    for(var i=0;i<datas.length;i++) {
      var childlist = datas[i].sub_categorys;
      var child = {};
      if(childlist) {
        child.id = datas[i].res_id;
        child.text = datas[i].res_name;
        child.leaf = false;
        child.icon = datas[i].icon;
        child.children = getResourceTree(childlist);
        root_children_list.push(child);
      } else {
        child.id = datas[i].res_id;
        child.text = datas[i].res_name;
        child.leaf = true;
        child.icon = datas[i].icon;
        child.hrefTarget = datas[i].res_url;
        root_children_list.push(child);
      }
    }
    return root_children_list;
  } else {
    return null;
  }
}